package com.basic.backend.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import javax.imageio.ImageIO;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class VideoProcessor {

    /**
     * 视频切片生成图片
     * @param videoFile  视频文件
     * @param outputDir  输出目录
     * @param intervalSec 截图间隔（秒）
     * @return 生成的图片文件列表
     */
    public static List<File> extractFrames(File videoFile, File outputDir, int intervalSec) 
        throws Exception {
        
        List<File> frameFiles = new ArrayList<>();
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFile)) {
            grabber.start();
            
            double frameRate = grabber.getFrameRate();
            int intervalFrames = (int) (frameRate * intervalSec);
            int totalFrames = grabber.getLengthInFrames();
            
            Java2DFrameConverter converter = new Java2DFrameConverter();
            for (int i = 0; i < totalFrames; i += intervalFrames) {
                grabber.setFrameNumber(i);
                Frame frame = grabber.grabImage();
                
                File outputFile = new File(outputDir, 
                    String.format("___%03d.png", frameFiles.size() + 1));
                ImageIO.write(converter.getBufferedImage(frame), "png", outputFile);
                frameFiles.add(outputFile);
            }
        }
        return frameFiles;
    }
}